package com.yunxi.service.localService.impl.sat;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunxi.core.service.ServiceImplPlus;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.dao.sat.SatCustomerClueMapper;
import com.yunxi.hubToBiz.pojo.CustomerTestDriveVO;
import com.yunxi.model.sat.PartnerCustomer;
import com.yunxi.model.sat.PartnerCustomerHis;
import com.yunxi.model.sat.SatCustomerClue;
import com.yunxi.model.sat.SatTestDrive;
import com.yunxi.sat.pojo.SatCustomerClueVO;
import com.yunxi.sat.pojo.SatMessAddVO;
import com.yunxi.sat.pojo.SatTestDriveVO;
import com.yunxi.sat.service.SatTestDriveDubboService;
import com.yunxi.service.localService.sat.*;
import com.yunxi.sys.pojo.StaffVO;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 客户线索 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-07-10
 */
@Service
public class SatCustomerClueServiceImpl extends ServiceImplPlus<SatCustomerClueMapper, SatCustomerClue> implements SatCustomerClueService {

    @Autowired
    @Qualifier(value = "partnerCustomerServiceImpl")
    PartnerCustomerService partnerCustomerService;

    @Autowired
    @Qualifier(value = "partnerCustomerHisServiceImpl")
    PartnerCustomerHisService partnerCustomerHisService;

    @Autowired
    @Qualifier(value = "satConfigServiceImpl")
    SatConfigService satConfigService;

    @Autowired
    @Qualifier(value = "satMessServiceImpl")
    SatMessService satMessService;

    @Autowired
    @Qualifier(value = "satTestDriveServiceImpl")
    SatTestDriveService satTestDriveService;

    @Autowired
    @Qualifier(value = "msgTemplateServiceImpl")
    MsgTemplateService msgTemplateService;

    @Autowired
    @Qualifier(value = "satTestDriveDubboServiceImpl")
    SatTestDriveDubboService satTestDriveDubboService;

    /**
     * 领取线索
     * @param satCustomerClueVO
     * @throws Exception
     */
    @Override
    @Transactional
    public void getClue(SatCustomerClueVO satCustomerClueVO, LoginInfo loginInfo) throws Exception {
        satCustomerClueVO.setPartnerCode(loginInfo.getPartnerCode());
//        String positionCode = getPositionCode(loginInfo);
        //销售经理没有领取数量限制
        //1.查询该销售顾问当前天已领取线索数量(只计算自己领取的线索,排除被分配的线索)
        Integer gotClueSum = baseMapper.queryGetClueSum(satCustomerClueVO);
        //2.查询销售助手配置,销售顾问每日可领取线索量
        Integer maxClueSum = baseMapper.querySatConfig(loginInfo.getUserCode());
        if(maxClueSum != null && gotClueSum > maxClueSum){
            if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())){
                throw new Exception("操作失败,已超过销售顾问每日可领取线索数量"+maxClueSum+"!");
            }
        }
        SatCustomerClue satCustomerClue = baseMapper.selectById(satCustomerClueVO.getClueId());
//        if (satCustomerClue.getIsRemindManager()==1) throw new Exception("该线索已超时,请刷新后重试");
        if(satCustomerClue != null){
            //校验已领取的线索不可再次领取
            checkClueIsGet(satCustomerClue);
            satCustomerClue.setGetUser(satCustomerClueVO.getGetUser());
            satCustomerClue.setIsGet(1);
            satCustomerClue.setIsSelf(1);
            satCustomerClue.setGetDate(new Date());
            satCustomerClue.setPartnerCode(satCustomerClueVO.getPartnerCode());
            baseMapper.updateById(satCustomerClue);
        }
        else{
            throw new Exception("操作失败,无法根据id:"+satCustomerClueVO.getClueId()+"找到对应线索!");
        }
        //3.新增客户与销售顾问关系,关系历史
//        addPartnerCustomer(satCustomerClueVO, satCustomerClue);

        //4.校验该客户是否存在未分配销售顾问的试驾信息,存在则分配给该线索领取人
        if ("2".equals(satCustomerClue.getClueType())) {
            assignTestDrive(satCustomerClueVO, satCustomerClue);
        }
    }

    /**
     * 校验已领取的线索不可再次领取/分配
     * @param satCustomerClue
     * @throws Exception
     */
    private void checkClueIsGet(SatCustomerClue satCustomerClue) throws Exception {
        Integer isGet = satCustomerClue.getIsGet();
        if (isGet != null && isGet.equals(1)) {
            throw new Exception("操作失败,线索已被领取!");
        }
    }

    /**
     * 分配线索
     * @param satCustomerClueVO
     * @throws Exception
     */
    @Override
    public void assignClue(SatCustomerClueVO satCustomerClueVO) throws Exception {
        String clueId = satCustomerClueVO.getClueId();
        String getUser = satCustomerClueVO.getGetUser();
        String assignUser = satCustomerClueVO.getAssignUser();
        SatCustomerClue satCustomerClue = baseMapper.selectById(clueId);
//        if (satCustomerClue.getIsRemindManager()==1) throw new Exception("该线索已超时,请刷新后重试");
        if(satCustomerClue != null){
            //校验已领取的线索不可再次分配
            checkClueIsGet(satCustomerClue);
            satCustomerClue.setGetUser(getUser);
            satCustomerClue.setAssignUser(assignUser);
            satCustomerClue.setIsSelf(0);
            satCustomerClue.setIsGet(1);
            satCustomerClue.setGetDate(new Date());
            satCustomerClue.setPartnerCode(satCustomerClueVO.getPartnerCode());
            baseMapper.updateById(satCustomerClue);

            //1.经理分配线索给销售顾问,需生成一条消息提醒给销售顾问
//            newMess(satCustomerClue,"1");//消息类型为新线索分配

        }
        else {
            throw new Exception("操作失败,无法根据id:"+clueId+"找到对应客户线索!");
        }
        //2.维护客户与销售顾问关系
//        addPartnerCustomer(satCustomerClueVO,satCustomerClue);

        //3.分配试驾信息
        if ( "2".equals(satCustomerClue.getClueType())) {
            assignTestDrive(satCustomerClueVO,satCustomerClue);
        }

        //4.生成消息给销售顾问
        pushMsg(satCustomerClueVO, getUser, satCustomerClue);
    }


    /**
     * 新增消息提醒
     * @param satCustomerClue
     * @param messType
     */
    /*@Override
    public void newMess(SatCustomerClue satCustomerClue,String messType) {
        SatMess satMess = new SatMess();
        satMess.setType(messType);//消息类型
        satMess.setSalesConsultantNo(satCustomerClue.getGetUser());
        String customerName = baseMapper.getCustomerNameByNo(satCustomerClue.getCustomerNo());
        satMess.setCustomerName(customerName);
        satMess.setCustomerNo(satCustomerClue.getCustomerNo());
        QueryWrapper<SatConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PARTNER_CODE",satCustomerClue.getPartnerCode());
        SatConfig satConfig = satConfigService.getOne(queryWrapper);
        if(satConfig != null && messType != null){
            switch (messType){
                case "1":
                    satMess.setInfo(satConfig.getNewClueMessInfo());
                    break;
                case "2":
                    satMess.setInfo(satConfig.getLostCustomerMessInfo());
                    break;
                case "3":
                    satMess.setInfo(satConfig.getHandleVehicleMessInfo());
                    break;
                case "4":
                    satMess.setInfo(satConfig.getTestAppraiseMessInfo());
                    break;
                case "5":
                    satMess.setInfo(satConfig.getTestRemindMessInfo());
                    break;
                case "7":
                    satMess.setInfo(satConfig.getLostTransferMessInfo());
                    break;
                case "8":
                    satMess.setInfo(satConfig.getNewCustomerMessInfo());
                    break;
                case "9":
                    satMess.setInfo(satConfig.getLostRejectMessInfo());
                    break;
            }
        }
        satMessService.saveOrUpdate(satMess);
    }*/

    /**
     * 分配线索给渠道商
     * @param satCustomerClueVO
     * @throws Exception
     */
    @Override
    public void assignClueToP(SatCustomerClueVO satCustomerClueVO) throws Exception {

    }

    /**
     * 根据用户姓名获取用户编号
     * @param userName
     * @return
     */
    @Override
    public String getUserCodeByName(String userName) {
        return baseMapper.getUserCodeByName(userName);
    }

    /**
     * 维护销售顾问和客户关系
     * @param satCustomerClueVO
     * @param satCustomerClue
     */
    private void addPartnerCustomer(SatCustomerClueVO satCustomerClueVO, SatCustomerClue satCustomerClue) {
        QueryWrapper<PartnerCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_NO",satCustomerClue.getCustomerNo());
        queryWrapper.eq("SALES_CONSULTANT_NO",satCustomerClueVO.getSalesConsultantNo());
        PartnerCustomer one = partnerCustomerService.getOne(queryWrapper);
        if(one == null){
            PartnerCustomer partnerCustomer = new PartnerCustomer();
            partnerCustomer.setPartnerCode(satCustomerClueVO.getPartnerCode());
            partnerCustomer.setCustomerNo(satCustomerClue.getCustomerNo());
            partnerCustomer.setSalesConsultantNo(satCustomerClueVO.getSalesConsultantNo());
            partnerCustomer.setCreateBy(satCustomerClueVO.getCreateBy());
            partnerCustomer.setUpdateBy(satCustomerClueVO.getCreateBy());
            partnerCustomerService.saveOrUpdate(partnerCustomer);
        }
        PartnerCustomerHis partnerCustomerHis = new PartnerCustomerHis();
        partnerCustomerHis.setPartnerCode(satCustomerClueVO.getPartnerCode());
        partnerCustomerHis.setCustomerNo(satCustomerClue.getCustomerNo());
        partnerCustomerHis.setSalesConsultantNo(satCustomerClueVO.getSalesConsultantNo());
        partnerCustomerHis.setCreateBy(satCustomerClueVO.getCreateBy());
        partnerCustomerHis.setUpdateBy(satCustomerClueVO.getCreateBy());
        partnerCustomerHisService.saveOrUpdate(partnerCustomerHis);
    }

    @Override
    public Integer todayClueCount(SatCustomerClueVO satCustomerClueVO)throws Exception{
        return baseMapper.todayClueCount(satCustomerClueVO);
    }

    /**
     * 查询超期线索
     * @return
     */
    @Override
    public List<SatCustomerClue> queryLateClue() {
        return baseMapper.queryLateClue();
    }

    /**
     * 查询销售经理超期线索
     * @return
     */
    @Override
    public List<SatCustomerClue> queryManagerLateClue() {
        return baseMapper.queryManagerLateClue();
    }

    @Override
    public String getCustomerNameByNo(SatCustomerClueVO satCustomerClueVO) {
        return baseMapper.getCustomerNameByNo(satCustomerClueVO);
    }

    /**
     * 线索返回小区经理
     * @param clueId
     */
    @Override
    public void returnAreaManager(String clueId) {
        baseMapper.returnAreaManager(clueId);
    }

   @Override
   public void updateBatch(Collection<SatCustomerClue> satCustomerClues) {
       baseMapper.updateBatch(satCustomerClues);
   }

    /**
     * 设置试驾信息所属渠道商
     * @param clueId
     * @throws Exception
     */
    @Override
    public void setTestDrivePartnerCode(String clueId,String salesConsultantNo) throws Exception {
        baseMapper.setTestDrivePartnerCode(clueId,salesConsultantNo);
    }

    /**
     * 分配试驾信息
     * @param satCustomerClueVO
     * @param satCustomerClue
     */
    private void assignTestDrive(SatCustomerClueVO satCustomerClueVO, SatCustomerClue satCustomerClue) throws Exception {
        List<SatTestDrive> list = satTestDriveService.queryEmptyTestDrive(satCustomerClue);
        if(list != null && list.size() > 0){
            for (SatTestDrive satTestDrive : list){
                satTestDrive.setSalesConsultantNo(satCustomerClueVO.getGetUser());
                satTestDrive.setPartnerCode(satCustomerClueVO.getPartnerCode());
                satTestDrive.setIsGet(1);
                satTestDrive.setGetUser(satCustomerClueVO.getGetUser());
                satTestDrive.setPartnerCode(satCustomerClue.getPartnerCode());
                satTestDriveService.saveOrUpdate(satTestDrive);

                //推送试驾到URM
                SatTestDriveVO satTestDriveVO = new SatTestDriveVO();
//                BeanUtils.copyProperties(satTestDriveVO,satTestDrive);
                satTestDriveVO.setCustomerNo(satTestDrive.getCustomerNo());
                satTestDriveVO.setSalesConsultantNo(satTestDrive.getSalesConsultantNo());
                satTestDriveVO.setPartnerCode(satTestDrive.getPartnerCode());
                satTestDriveVO.setCustomerName(satTestDrive.getCustomerName());
                satTestDriveVO.setPlanDriveTime(satTestDrive.getPlanDriveTime());
                satTestDriveVO.setIsGet(satTestDrive.getIsGet());
                satTestDriveVO.setGetUser(satTestDrive.getGetUser());
                satTestDriveVO.setAddress(satTestDrive.getAddress());
                satTestDriveVO.setCityCode(satTestDrive.getCityCode());
                satTestDriveVO.setDriveStyle(satTestDrive.getDriveStyle());
                satTestDriveVO.setApplyType(satTestDrive.getApplyType());
                satTestDriveVO.setCertPicFront(satTestDrive.getCertPicFront());
                satTestDriveVO.setCertPicBack(satTestDrive.getCertPicBack());

                satTestDriveDubboService.pushTestDriveToURM(satTestDriveVO);
            }
        }
    }

    /**
     * 获取职位代码
     * @param loginInfo
     * @return
     */
    private String getPositionCode(LoginInfo loginInfo) {
        Object staff = loginInfo.getStaff();
        String positionCode = null;
        if(staff != null){
            StaffVO staffVO = JSONObject.parseObject(JSONObject.toJSONString(staff), StaffVO.class);
            positionCode = staffVO.getPositionCode();
        }
        return positionCode;
    }

    /**
     * 生成消息
     * @param satCustomerClueVO
     * @param getUser
     * @param satCustomerClue
     */
    private void pushMsg(SatCustomerClueVO satCustomerClueVO, String getUser, SatCustomerClue satCustomerClue) throws InvocationTargetException, IllegalAccessException {
        SatMessAddVO satMessAddVO = new SatMessAddVO();
        satMessAddVO.setType("1");
        satMessAddVO.setTemplateType(2);
        satMessAddVO.setCustomerName(satCustomerClue.getCustomerName());
        satMessAddVO.setCustomerNo(satCustomerClue.getCustomerNo());
        satMessAddVO.setSalesConsultantNo(getUser);
        satMessAddVO.setReceiveRoleCode("rolePartnerSale");
        satMessAddVO.setOperaRoleCode(satCustomerClueVO.getOperaRoleCode());
        satMessService.newMess(satMessAddVO);
    }
}
